package com.erp.action;

import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.erp.dto.Page;
import com.erp.dto.Privilege;
import com.erp.dto.Role;
import com.erp.util.PrivilegeUtil;

@SuppressWarnings("serial")
@Controller(value = "roleAction")
@Scope(value = "prototype")
public class RoleAction extends ModelDrivenBaseAction<Role> {

	private Integer[] privilegeIds;

	public Integer[] getPrivilegeIds() {
		return privilegeIds;
	}

	public void setPrivilegeIds(Integer[] privilegeIds) {
		this.privilegeIds = privilegeIds;
	}

	/**
	 * 添加页面
	 */
	public String addPage() throws Exception {

		return "addPage";
	}

	/**
	 * 添加操作
	 */
	public void add() throws Exception {
		roleService.add(model, true);
		writeJson("msg", "true");
	}

	/**
	 * 删除操作
	 */
	public void delete() throws Exception {
		// System.out.println(this.getClass().getSimpleName());
		roleService.delete(model);
		writeJson("msg", "true");
	}

	/**
	 * 编辑页面
	 */
	public String editPage() throws Exception {
		model = roleService.getRoleById(model.getId());
		pushIntoValueStack(model);
		return "editPage";
	}

	/**
	 * 获取角色的描述
	 * 
	 * @throws Exception
	 */
	public void getDescription() throws Exception {
		model = roleService.getRoleById(model.getId());
		String description = model.getDescription();
		if (description == null || "".equals(description.trim())) {
			writeJson("description", "暂无描述");
		} else {
			writeJson("description", description);
		}
	}


	/**
	 * 编辑操作
	 */
	public void edit() throws Exception {
		roleService.update(model);
		writeJson("msg", "true");
	}

	/**
	 * 岗位列表
	 */
	public String list() throws Exception {
		if (page == null) {
			page = new Page();
		}
		return pagedList();
	}

	/**
	 * 所有岗位列表
	 */
	public String listAll() throws Exception {
		request.put("roleList", roleService.listAll());
		return "list";
	}

	/**
	 * 分页后的岗位列表
	 */
	public String pagedList() throws Exception {
		request.put("roleList", roleService.getPagedList(page));
		pushIntoValueStack(page);
		return "list";
	}

	/**
	 * 设置权限页面
	 */
	public String setPrivilegePage() throws Exception {
		model = roleService.getRoleById(model.getId());
		request.put(
				"zNodes",
				PrivilegeUtil.toPrivilegeTree(privilegeService.list(),
						model.getPrivilegeList()));
		return "setPrivilegePage";
	}

	/**
	 * 设置权限
	 */
	public void setPrivilege() throws Exception {
		List<Privilege> privilegeList = roleService
				.getPrivilegeListByArray(privilegeIds);
		if (privilegeList != null) {
			model.setPrivilegeList(privilegeList);
		}
		roleService.setRolePrivilege(model);
		writeJson("msg", "true");
	}

}
